<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
namespace core;
defined('BY_JYA') or exit('error');
class tools{
	//获取文件大小，转换为便于读写、理解的格式
	public function sizecount($size) {
		if($size >= 1073741824) {
			$size = round($size / 1073741824 * 100) / 100 . ' GB';
		} elseif($size >= 1048576) {
			$size = round($size / 1048576 * 100) / 100 . ' MB';
		} elseif($size >= 1024) {
			$size = round($size / 1024 * 100) / 100 . ' KB';
		} else {
			$size = $size . ' Bytes';
		}
		return $size;
	}
	public function set_str($str,$rep,$head=0,$tail=0,$long=false){
	//参数说明，$str：要整理的字符串；$head：头部截取位数；$tail：尾部截取位数；$rep：中间部分替代字符串,$long：是否单个字符替换
		$num=strlen($str);
		if($num>($head+$tail)){
			$search=array();
			if($head){
				$search[]=substr($str,0,$head);
			}
			if($tail){
				$search[]=substr($str,-$tail);
			}
			if($long){
				$str=str_replace($search,'',$str);
				$num=strlen($str);
				$m='';
				for($i=0;$i<$num;$i++){
					$m.=$rep;
				}
			}else{
				$m=$rep;
			}
			if($head && $tail){
				$return=$search['0'].$m.$search['1'];
			}elseif($head){
				$return=$search['0'].$m;
			}elseif($tail){
				$return=$m.$search['0'];
			}else{
				$return=$m;
			}
			
			return $return;
		}else{
			return $str;
		}
	}
	//导出excel
	public function export2excel($header,$data,$filename,$headerkey=false,$save_filename=''){
		$html="\xEF\xBB\xBF";
		if($headerkey){
			foreach ($header as $k=>$li) {
				$html .= $k . "\t ,";
			}
			$html.="\n";
		}
		foreach ($header as $li) {
			$html .= $li . "\t ,";
		}
		$html.="\n";
		$keys=array_keys($header);
		foreach($data as $row){
			foreach($keys as $key){
				$cont=str_replace(',','|jy|',$row[$key]);
				$html.=$cont."\t,";
			}
			$html.="\n";
		}
		if($save_filename){
			$filename=iconv("UTF-8","gbk",$filename);
			$save_filename=$save_filename.'/'.$filename.'.csv';
			model('core/files')->source_save($html,'','csv',$filename,$save_filename,'','',true);
			return true;
		}
		ob_clean();
		header("Content-type:text/csv");
		header("Content-Disposition:attachment; filename=".$filename.".csv");
		echo $html;
		exit();
	}
	//下载zip
	public function down_zip($dir,$filename='',$deldir=false){
		//下载包
		$filename=$filename?:random(10);
		do{
			$zip=ROOT_AT.random(10).'.temp';			
		}while(is_file($zip));
		cfc('files')->zip($dir,$zip);
		header('content-type: application/zip');
		header('content-disposition: attachment; filename="' . $filename . '.zip"');
		readfile($zip);
		@unlink($zip);
		if($deldir){
			@unlink($dir);
		}
		exit();
	}
	//导入excel
	public function importExcel($file){
		if (!file_exists($file)) {
			exi('excel文件不存在！无法导入！','error');
		}
		require_once ROOT_D.'/core/library/phpexcel/PHPExcel.php';
		require_once ROOT_D.'/core/library/phpexcel/PHPExcel/IOFactory.php';
		require_once ROOT_D.'/core/library/phpexcel/PHPExcel/Reader/CSV.php';
		$objReader = \PHPExcel_IOFactory::createReader('CSV')->setInputEncoding('UTF-8');//use excel2007 for 2007 format
		$objPHPExcel = $objReader->load($file);
		$sheet = $objPHPExcel->getSheet(0);
		$highestRow = $sheet->getHighestRow(); // 取得总行数
		$highestColumn = $sheet->getHighestColumn(); // 取得总列数
		$objWorksheet = $objPHPExcel->getActiveSheet();
		$highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
		$excelData = array();
		for ($row = 1; $row <= $highestRow; $row++) {
			for ($col = 0; $col < $highestColumnIndex; $col++) {
				$value=(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
				$excelData[$row][] =trim($value);
			}
		}
		return $excelData;
	}
	public function is_base64($str){
		if(!is_string($str)){
			return false;
		}
		return $str == base64_encode(base64_decode($str));
	}
	public function range_limit($num, $downline, $upline, $returnNear = true) {
		$num = intval($num);
		$downline = intval($downline);
		$upline = intval($upline);
		if($num < $downline){
			return empty($returnNear) ? false : $downline;
		} elseif ($num > $upline) {
			return empty($returnNear) ? false : $upline;
		} else {
			return empty($returnNear) ? true : $num;
		}
	}
	public function is_serialized($data, $strict = true) {
		if (!is_string($data)) {
			return false;
		}
		$data = trim($data);
		if ('N;' == $data) {
			return true;
		}
		if (strlen($data) < 4) {
			return false;
		}
		if (':' !== $data[1]) {
			return false;
		}
		if ($strict) {
			$lastc = substr($data, -1);
			if (';' !== $lastc && '}' !== $lastc) {
				return false;
			}
		} else {
			$semicolon = strpos($data, ';');
			$brace = strpos($data, '}');
					if (false === $semicolon && false === $brace)
				return false;
					if (false !== $semicolon && $semicolon < 3)
				return false;
			if (false !== $brace && $brace < 4)
				return false;
		}
		$token = $data[0];
		switch ($token) {
			case 's' :
				if ($strict) {
					if ('"' !== substr($data, -2, 1)) {
						return false;
					}
				} elseif (false === strpos($data, '"')) {
					return false;
				}
					case 'a' :
			case 'O' :
				return (bool)preg_match("/^{$token}:[0-9]+:/s", $data);
			case 'b' :
			case 'i' :
			case 'd' :
				$end = $strict ? '$' : '';
				return (bool)preg_match("/^{$token}:[0-9.E-]+;$end/", $data);
		}
		return false;
	}
	public function referer($default = '') {
		global $_RQ, $_AR;
		$_SESSION['referer'] = !empty($_RQ['referer']) ? $_RQ['referer'] : $_SERVER['HTTP_REFERER'];;
		$_SESSION['referer'] = substr($_SESSION['referer'], -1) == '?' ? substr($_SESSION['referer'], 0, -1) : $_SESSION['referer'];

		if (strpos($_SESSION['referer'], 'member.php?act=login')) {
			$_SESSION['referer'] = $default;
		}
		$_SESSION['referer'] = $_SESSION['referer'];
		$_SESSION['referer'] = str_replace('&amp;', '&', $_SESSION['referer']);
		$reurl = parse_url($_SESSION['referer']);

		if (!empty($reurl['host']) && !in_array($reurl['host'], array($_SERVER['HTTP_HOST'], 'www.' . $_SERVER['HTTP_HOST'])) && !in_array($_SERVER['HTTP_HOST'], array($reurl['host'], 'www.' . $reurl['host']))) {
			$_SESSION['referer'] = $_SESSION['siteroot'];
		} elseif (empty($reurl['host'])) {
			$_SESSION['referer'] = $_SESSION['siteroot'] . './' . $_SESSION['referer'];
		}
		return strip_tags($_SESSION['referer']);
	}
	public function scriptname() {
		global $_AR;
		$_AR['script_name'] = basename($_SERVER['SCRIPT_FILENAME']);
		if(basename($_SERVER['SCRIPT_NAME']) === $_AR['script_name']) {
			$_AR['script_name'] = $_SERVER['SCRIPT_NAME'];
		} else {
			if(basename($_SERVER['PHP_SELF']) === $_AR['script_name']) {
				$_AR['script_name'] = $_SERVER['PHP_SELF'];
			} else {
				if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $_AR['script_name']) {
					$_AR['script_name'] = $_SERVER['ORIG_SCRIPT_NAME'];
				} else {
					if(($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
						$_AR['script_name'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $_AR['script_name'];
					} else {
						if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'], $_SERVER['DOCUMENT_ROOT']) === 0) {
							$_AR['script_name'] = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $_SERVER['SCRIPT_FILENAME']));
						} else {
							$_AR['script_name'] = 'unknown';
						}
					}
				}
			}
		}
		return $_AR['script_name'];
	}
	//截取utf8格式字符串，功能和substr函数类似，$start只能为正数或者0
	public function substr($string,$start,$length=0){
		$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&','"','<','>'), $string);
		$num=strlen($string);
		$i=$count=0;
		while($i<$num){
			$t = ord($string[$i]);
			if($count==$start){
				$s=$i;
				//如果没有限制截取长度，找到开始截取位置即返回
				if(!$length){
					break;
				}
			}
			if($count==$start+$length){
				$e=$i;
				break;
			}
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$i++;
			}elseif (194 <= $t && $t <= 223) {
				$i += 2;
			} elseif (224 <= $t && $t <= 239) {
				$i += 3;
			} elseif (240 <= $t && $t <= 247) {
				$i += 4;
			} elseif (248 <= $t && $t <= 251) {
				$i += 5;
			} elseif ($t == 252 || $t == 253) {
				$i+=6;
			} else {
				$i++;
			}
			$count++;
		}
		if($e){
			$l=$e-$s;
			$result=substr($string,$s,$l);
		}else{
			$result=substr($string,$s);
		}
		$result= str_replace(array('&','"','<','>'),array('&amp;', '&quot;', '&lt;', '&gt;'), $result);
		return $result;
	}
	//截取字符串
	public function cutstr($string, $length, $havedot = false, $charset = '') {
		global $_AR;
		if (empty($charset)) {
			$charset = CHARSET;
		}
		if (strtolower($charset) == 'gbk') {
			$charset = 'gbk';
		} else {
			$charset = 'utf8';
		}
		if ($this->istrlen($string, $charset) <= $length) {
			return $string;
		}
		if (function_exists('mb_strcut')) {
			$string = mb_substr($string, 0, $length, $charset);
		} else {
			$pre = '{%';
			$end = '%}';
			$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), $string);

			$strcut = '';
			$strlen = strlen($string);

			if ($charset == 'utf8') {
				$n = $tn = $noc = 0;
				while ($n < $strlen) {
					$t = ord($string[$n]);
					if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
						$tn = 1;
						$n++;
						$noc++;
					} elseif (194 <= $t && $t <= 223) {
						$tn = 2;
						$n += 2;
						$noc++;
					} elseif (224 <= $t && $t <= 239) {
						$tn = 3;
						$n += 3;
						$noc++;
					} elseif (240 <= $t && $t <= 247) {
						$tn = 4;
						$n += 4;
						$noc++;
					} elseif (248 <= $t && $t <= 251) {
						$tn = 5;
						$n += 5;
						$noc++;
					} elseif ($t == 252 || $t == 253) {
						$tn = 6;
						$n += 6;
						$noc++;
					} else {
						$n++;
					}
					if ($noc >= $length) {
						break;
					}
				}
				if ($noc > $length) {
					$n -= $tn;
				}
				$strcut = substr($string, 0, $n);
			} else {
				while ($n < $strlen) {
					$t = ord($string[$n]);
					if ($t > 127) {
						$tn = 2;
						$n += 2;
						$noc++;
					} else {
						$tn = 1;
						$n++;
						$noc++;
					}
					if ($noc >= $length) {
						break;
					}
				}
				if ($noc > $length) {
					$n -= $tn;
				}
				$strcut = substr($string, 0, $n);
			}
			$string = str_replace(array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
		}

		if ($havedot) {
			$string = $string . "...";
		}

		return $string;
	}
	//计算字符串长度
	public function istrlen($string, $charset = '') {
		global $_AR;
		if (empty($charset)) {
			$charset = CHARSET;
		}
		if (strtolower($charset) == 'gbk') {
			$charset = 'gbk';
		} else {
			$charset = 'utf8';
		}
		if (function_exists('mb_strlen')) {
			return mb_strlen($string, $charset);
		} else {
			$n = $noc = 0;
			$strlen = strlen($string);

			if ($charset == 'utf8') {
				while ($n < $strlen) {
					$t = ord($string[$n]);
					if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
						$n++;
						$noc++;
					} elseif (194 <= $t && $t <= 223) {
						$n += 2;
						$noc++;
					} elseif (224 <= $t && $t <= 239) {
						$n += 3;
						$noc++;
					} elseif (240 <= $t && $t <= 247) {
						$n += 4;
						$noc++;
					} elseif (248 <= $t && $t <= 251) {
						$n += 5;
						$noc++;
					} elseif ($t == 252 || $t == 253) {
						$n += 6;
						$noc++;
					} else {
						$n++;
					}
				}

			} else {

				while ($n < $strlen) {
					$t = ord($string[$n]);
					if ($t > 127) {
						$n += 2;
						$noc++;
					} else {
						$n++;
						$noc++;
					}
				}

			}

			return $noc;
		}
	}


	public function emotion($message = '', $size = '24px') {
		$emotions = array(
			"/::)","/::~","/::B","/::|","/:8-)","/::<","/::$","/::X","/::Z","/::'(",
			"/::-|","/::@","/::P","/::D","/::O","/::(","/::+","/:--b","/::Q","/::T",
			"/:,@P","/:,@-D","/::d","/:,@o","/::g","/:|-)","/::!","/::L","/::>","/::,@",
			"/:,@f","/::-S","/:?","/:,@x","/:,@@","/::8","/:,@!","/:!!!","/:xx","/:bye",
			"/:wipe","/:dig","/:handclap","/:&-(","/:B-)","/:<@","/:@>","/::-O","/:>-|",
			"/:P-(","/::'|","/:X-)","/::*","/:@x","/:8*","/:pd","/:<W>","/:beer","/:basketb",
			"/:oo","/:coffee","/:eat","/:pig","/:rose","/:fade","/:showlove","/:heart",
			"/:break","/:cake","/:li","/:bome","/:kn","/:footb","/:ladybug","/:shit","/:moon",
			"/:sun","/:gift","/:hug","/:strong","/:weak","/:share","/:v","/:@)","/:jj","/:@@",
			"/:bad","/:lvu","/:no","/:ok","/:love","/:<L>","/:jump","/:shake","/:<O>","/:circle",
			"/:kotow","/:turn","/:skip","/:oY","/:#-0","/:hiphot","/:kiss","/:<&","/:&>"
		);
		foreach ($emotions as $index => $emotion) {
			$message = str_replace($emotion, '<img style="width:'.$size.';vertical-align:middle;" src="http://res.mail.qq.com/zh_CN/images/mo/DEFAULT2/'.$index.'.gif" />', $message);
		}
		return $message;
	}


	public function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
		$ckey_length = 4;
		$key = md5($key != '' ? $key : $GLOBALS['_W']['config']['setting']['authkey']);
		$keya = md5(substr($key, 0, 16));
		$keyb = md5(substr($key, 16, 16));
		$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

		$cryptkey = $keya . md5($keya . $keyc);
		$key_length = strlen($cryptkey);

		$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
		$string_length = strlen($string);

		$result = '';
		$box = range(0, 255);

		$rndkey = array();
		for ($i = 0; $i <= 255; $i++) {
			$rndkey[$i] = ord($cryptkey[$i % $key_length]);
		}

		for ($j = $i = 0; $i < 256; $i++) {
			$j = ($j + $box[$i] + $rndkey[$i]) % 256;
			$tmp = $box[$i];
			$box[$i] = $box[$j];
			$box[$j] = $tmp;
		}

		for ($a = $j = $i = 0; $i < $string_length; $i++) {
			$a = ($a + 1) % 256;
			$j = ($j + $box[$a]) % 256;
			$tmp = $box[$a];
			$box[$a] = $box[$j];
			$box[$j] = $tmp;
			$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
		}

		if ($operation == 'DECODE') {
			if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
				return substr($result, 26);
			} else {
				return '';
			}
		} else {
			return $keyc . str_replace('=', '', base64_encode($result));
		}

	}
	public function utf8_bytes($cp) {
		if ($cp > 0x10000){
					return	chr(0xF0 | (($cp & 0x1C0000) >> 18)).
			chr(0x80 | (($cp & 0x3F000) >> 12)).
			chr(0x80 | (($cp & 0xFC0) >> 6)).
			chr(0x80 | ($cp & 0x3F));
		}else if ($cp > 0x800){
					return	chr(0xE0 | (($cp & 0xF000) >> 12)).
			chr(0x80 | (($cp & 0xFC0) >> 6)).
			chr(0x80 | ($cp & 0x3F));
		}else if ($cp > 0x80){
					return	chr(0xC0 | (($cp & 0x7C0) >> 6)).
			chr(0x80 | ($cp & 0x3F));
		}else{
					return chr($cp);
		}
	}
	//aes解密
	public function aes_decode($message, $encodingaeskey = '', $appid = '') {
		$key = base64_decode($encodingaeskey . '=');

		$ciphertext_dec = base64_decode($message);
		$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
		$iv = substr($key, 0, 16);

		mcrypt_generic_init($module, $key, $iv);
		$decrypted = mdecrypt_generic($module, $ciphertext_dec);
		mcrypt_generic_deinit($module);
		mcrypt_module_close($module);
		$block_size = 32;

		$pad = ord(substr($decrypted, -1));
		if ($pad < 1 || $pad > 32) {
			$pad = 0;
		}
		$result = substr($decrypted, 0, (strlen($decrypted) - $pad));
		if (strlen($result) < 16) {
			return '';
		}
		$content = substr($result, 16, strlen($result));
		$len_list = unpack("N", substr($content, 0, 4));
		$contentlen = $len_list[1];
		$content = substr($content, 4, $contentlen);
		$from_appid = substr($content, $xml_len + 4);
		if (!empty($appid) && $appid != $from_appid) {
			return '';
		}
		return $content;
	}
	//aes加密
	public function aes_encode($message, $encodingaeskey = '', $appid = '') {
		$key = base64_decode($encodingaeskey . '=');
		$text = random(16) . pack("N", strlen($message)) . $message . $appid;

		$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
		$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
		$iv = substr($key, 0, 16);

		$block_size = 32;
		$text_length = strlen($text);
			$amount_to_pad = $block_size - ($text_length % $block_size);
		if ($amount_to_pad == 0) {
			$amount_to_pad = $block_size;
		}
			$pad_chr = chr($amount_to_pad);
		$tmp = '';
		for ($index = 0; $index < $amount_to_pad; $index++) {
			$tmp .= $pad_chr;
		}
		$text = $text . $tmp;
		mcrypt_generic_init($module, $key, $iv);
			$encrypted = mcrypt_generic($module, $text);
		mcrypt_generic_deinit($module);
		mcrypt_module_close($module);
			$encrypt_msg = base64_encode($encrypted);
		return $encrypt_msg;
	}
	public function ihtml_entity_decode($str) {
		$str = str_replace('&nbsp;', '#nbsp;', $str);
		return str_replace('#nbsp;', '&nbsp;', html_entity_decode(urldecode($str)));
	}
	
	public function iarray_change_key_case($array, $case = CASE_LOWER){
		if (!is_array($array) || empty($array)){
			return array();
		}
		$array = array_change_key_case($array, $case);
		foreach ($array as $key => $value){
			if (empty($value) && is_array($value)) {
				$array[$key] = '';
			}
			if (!empty($value) && is_array($value)) {
				$array[$key] = $this->iarray_change_key_case($value, $case);
			}
		}
		return $array;
	}
	public function combile($source,$data,$pre=''){
		if(!is_array($data) || empty($data)){
			return $source;
		}
		foreach($data as $key=>$value){
			if(is_array($value)){
				$source=$this->combile($source,$value,$pre.$key.'.');
			}else{
				$source=str_replace('{'.$pre.$key.'}',$value,$source);
			}
		}
		return $source;
	}
	//字符串替换
	public function replace($search,$string){
		$search=$this->combile1($search);
		$seh=$rep=array();
		foreach($search as $key=>$value){
			$seh[]=$key;
			$rep[]=$value;
		}
		$string=str_replace($seh,$rep,$string);
		return $string;
	}
	public function combile1($search,$pre=''){
		if(!is_array($search)){
			return false;
		}
		$result=array();
		foreach($search as $key=>$value){
			if(is_array($value)){
				if($value){
					$res=$this->combile1($value,$pre.$key.'.');
					$result=array_merge($result,$res);
				}
				
			}else{
				$result['{'.$pre.$key.'}']=$value;
			}
		}
		return $result;
	}
	public function pcd(){
		$res=file_get_contents(ROOT_D.'/core/resource/area_town.txt');
		$res=unserialize($res);
		return $res;
	}
	//base64加密
	public function base64_encode($str,$key_str=''){
		if(!$key_str){
			$key_str=BASE64_KEY;
		}
		if(!$key_str){
			$key_str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
		}
		$num=strlen($str);
		$i=0;
		$res='';
		$more=0;
		while($i<$num){
			$s1=$this->to2str($str[$i]);
			if($i+1<$num){
				$s2=$this->to2str($str[$i+1]);
			}else{
				$s2='00000000';
				$more=2;
			}
			if($i+2<$num){
				$s3=$this->to2str($str[$i+2]);
			}else{
				$s3='00000000';
				if(!$more){
					$more=1;
				}
			}
			$s=$s1.$s2.$s3;
			$e1=$this->to10str($s,0,$key_str);
			$e2=$this->to10str($s,1,$key_str);
			$e3=$this->to10str($s,2,$key_str);
			$e4=$this->to10str($s,3,$key_str);
			$e=$e1.$e2.$e3.$e4;
			$res.=$e;
			$i+=3;
		}
		if($more==1){
			$res=substr_replace($res,$key_str['64'],-1);
		}elseif($more==2){
			$res=substr_replace($res,$key_str['64'].$key_str['64'],-2);
		}
		return $res;
	}
	//base64解密
	public function base64_decode($str,$key_str=''){
		
		if(!$key_str || strlen($key_str)!=65){
			$key_str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
		}
		$key_array=str_split($key_str);
		$key_array=array_flip($key_array);
		//计算补充了多少位
		$all=strlen($str);
		$old_str=trim($str,$key_str['64']);
		$num=strlen($old_str);
		$more=$all-$num;
		if($more==1){
			$old_str.=$key_str['0'];
		}elseif($more==2){
			$old_str.=$key_str['0'].$key_str['0'];
		}
		//开始解密字符串
		$i=0;
		$str2='';
		while($i<$all){
			$e=$key_array[$old_str[$i]];
			$e=decbin($e);
			$e=sprintf("%'06s",$e);
			$str2.=$e;
			$i++;
		}
		$j=0;
		$num2=strlen($str2);
		//减去补充的部分
		$num2=$num2-$more*8;
		$de_str='';
		while($j*8<$num2){
			$s=substr($str2,$j*8,8);
			$s=bindec($s);
			$de_str.=chr($s);
			$j++;
		}
		return $de_str;
	}
	private function to2str($s){
		$s=ord($s);
		$s=decbin($s);
		$s=sprintf("%'08s",$s);
		return $s;
	}
	private function to10str($str,$num,$key_str){
		$e=substr($str,$num*6,6);
		$e=bindec($e);
		return $key_str[$e];
	}
	function var_export($data,$t=''){
		if(is_numeric($data)){
			return $data;
		}elseif(is_string($data)){
			$data=str_replace(array('\\',"'"),array('\\\\',"\\'"),$data);
			return "'$data'";
		}elseif(is_bool($data)){
			return $data?'true':'false';
		}
		if(!is_array($data)){
			
			return 'null';
		}
		if(empty($data)){
			return 'array()';
		}
		$string='array(';
		if($this->isAssocArray($data)){
			//数值型数组
			foreach($data as $value){
				$string.="\n{$t}\t".$this->var_export($value,$t."\t").',';
			}
			$string.="\n{$t})";
		}else{
			if(count($data)>5){
				foreach($data as $key=>$value){
					$string.="\n{$t}\t'{$key}'=>".$this->var_export($value,$t."\t").',';
				}
				$string.="\n{$t})";
			}else{
				foreach($data as $key=>$value){
					$string.="'{$key}'=>".$this->var_export($value,$t).',';
				}
				$string.=')';
			}
			
		}
		
		return $string;
	}
	function isAssocArray($arr){
        if(!is_array($arr)){
			return false;
		}
		if(!isset($arr[0])){
			//PHP会判断 0 和任意字符串相等，因此下面的判断无法正确判断只有一个元素的关联数组，此处补充判断！
			return false;
		}
		$arr=array_keys($arr);
		$index = 0;
        foreach ($arr as $key){
            if ($index++ != $key) return false;
        }
        return true;
    }
	//过滤敏感词
	public function filterword($content,$keywords){
		if(!empty($keywords)){
			$keywords = explode("|",$keywords);
			foreach($keywords as $k=>$v){
				if(!empty($v)){
					$content = str_replace($v,"***",$content);
				}
			}
		}
		$content = str_replace("\n","<br>",$content);
		return $content;
	}
	public function get_distance_by_lnt($lnt1, $lnt2) {
		return $this->getdistance($lnt1['lng'], $lnt1['lat'], $lnt2['lng'], $lnt2['lat']);
	}
	public function getdistance($lng1, $lat1, $lng2, $lat2) {
    // 将角度转为狐度
		if(!$lng1 || !$lng2 || !$lat1 || !$lat2){
			return false;
		}
		$radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
		$radLat2 = deg2rad($lat2);
		$radLng1 = deg2rad($lng1);
		$radLng2 = deg2rad($lng2);
		$a = $radLat1 - $radLat2;
		$b = $radLng1 - $radLng2;
		$s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
		return $s;
	}
	//文档：https://lbs.amap.com/api/webservice/guide/api/georegeo/
	public function getgeocode($address, $key = 0)
	{
		if (empty($key)) {
			$key = '4aedf9c53d024018dd6739435a5a1c60';
		}

		$address = str_replace(' ', '', $address);
		$url = 'http://restapi.amap.com/v3/geocode/geo?address=' . $address . '&key=' . $key;
		$contents = file_get_contents($url);
		$data = json_decode($contents, true);
		if($data['status']==0){
			return $data;
			//exi('请填写有效地址，城市区域不能为空，详细地址要准确有效！','error');
		}else{
			return $data;
		}
	}
	public function createqrcode($url,$size=150,$file=false,$filename=''){
		require_once  ROOT_D .'/core/library/qrcode/phpqrcode.php';		
		$value = $url;					//二维码内容		
		$errorCorrectionLevel = 'L';	//容错级别 				
		$j = floor($size/40*100)/100 ; //生成图片大小  
		//生成二维码图片
		$filename = $filename?:ROOT_AT.random(30).'.png';		
		\QRcode::png($value,$filename , $errorCorrectionLevel, $j, 2);  
		if($file){
			$qr=cfc('files')->source_save($filename,'data','png','二维码','','',$url);
			$this->add_qrcodelogo($qr);
		}else{
			$qr = file_get_contents($filename);
		}
		unlink($filename);
		return $qr;   
	}
	public function add_qrcodelogo($qr,$logo=''){
		$qr=$filename=ROOT_AT.$qr;
		$logo=$logo?:$_SESSION['account']['logo'];
		if ($logo) {
			$logo=tomedia($logo);
			$qr = imagecreatefromstring(file_get_contents($qr));
			$logo = imagecreatefromstring(file_get_contents($logo));
			$qr_width = imagesx($qr);//二维码图片宽度
			$qr_height = imagesy($qr);//二维码图片高度
			$logo_width = imagesx($logo);//logo图片宽度
			$logo_height = imagesy($logo);//logo图片高度
			$logo_qr_width = $qr_width / 5; //logo图片在二维码图片中宽度大小
			$scale = $logo_width/$logo_qr_width;
			$logo_qr_height = $logo_height/$scale; //logo图片在二维码图片中高度大小
			$from_width = ($qr_width - $logo_qr_width) / 2;
			if($logo_qr_width && $logo_qr_height){
				//重新组合图片并调整大小
				imagecopyresampled($qr, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
				imagepng($qr,$filename); 
			}
		}
		return true;
	}
	public function createwxppqrcode($url,$size=150,$system=false){
		if($system){
			$uniacid=1;
		}else{
			$uniacid=$_SESSION['uniacid'];
		}
		
		$path='/pages/html/html?url='.$url;
		//获取小程序ID
		$id=pdo_getcolumn('core_account_wxapp_info',array('uniacid'=>$uniacid),'default_wxapp');
		if($id){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$id));
		}else{
			$wxapp=pdo_get('core_account_wxapp',array('uniacid'=>$uniacid));
		}
		if(!$wxapp || !$wxapp['appid'] || !$wxapp['appsecret']){
			return false;
		}
		$attachment=pdo_getcolumn('core_account_wxapp_ewm',array('wxapp_id'=>$wxapp['id'],'action'=>$url),'attachment');
		if(!$attachment){
				
				$data=model('core/wxapp')->appcode($path,$wxapp['appid'],$wxapp['appsecret'],200);
				if(!$data){
					return false;
				}
				$attachment=model('core/files')->source_save($data,'data','jpg');
				$insert=array(
					'uniacid'=>$uniacid,
					'wxapp_id'=>$wxapp['id'],
					'action'=>$url,
					'attachment'=>$attachment,
				);
				pdo_insert('core_account_wxapp_ewm',$insert);
		}
		return $attachment;
	}
	public function create_check_code($string,$seckey,$len){
		$temp=sha1($string.$seckey);
		$code='';
		for($i=0;$i<$len;$i++){
			$a=ord($temp[$i]);
			$code.=substr($a,-1);
		}
		return $code;
	}
	public function upnickname($name=''){
		if($name){
             $name = preg_replace_callback( '/./u',function (array $match) {
				return strlen($match[0]) >= 4 ? '' : $match[0];
			  },$name);
		   $name=trim($name)?:'特殊字符昵称';
		   return $name;
        }else{
           return '';
        }
	}
	function Convert_GCJ02_To_BD09($lat,$lng){
		$x_pi = 3.14159265358979324 * 3000.0 / 180.0;
		$x = $lng;
		$y = $lat;
		$z =sqrt($x * $x + $y * $y) + 0.00002 * sin($y * $x_pi);
		$theta = atan2($y, $x) + 0.000003 * cos($x * $x_pi);
		$lng = $z * cos($theta) + 0.0065;
		$lat = $z * sin($theta) + 0.006;
		return array('lng'=>$lng,'lat'=>$lat);
	}
	function Convert_BD09_To_GCJ02($lat,$lng){
		$x_pi = 3.14159265358979324 * 3000.0 / 180.0;
		$x = $lng - 0.0065;
		$y = $lat - 0.006;
		$z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
		$theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
		$lng = $z * cos($theta);
		$lat = $z * sin($theta);
		return array('lng'=>$lng,'lat'=>$lat);
	}
	public function checkrobot($useragent='',$isssr=false){
		if($isssr){
			return true;
		}
		static $kw_spiders = array('bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla');
		static $kw_browsers = array('msie', 'netscape', 'opera', 'konqueror', 'mozilla');	 
		$useragent = strtolower(empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent);
		if(strpos($useragent, 'http://') === false && $this->dstrpos($useragent, $kw_browsers)){
			return false;
		}
		if($this->dstrpos($useragent, $kw_spiders)){
			return true;
		}
		return false;
	}
	public function dstrpos($string, $arr, $returnvalue = false) {
		if(empty($string)) return false;
		foreach((array)$arr as $v) {
			if(strpos($string, $v) !== false) {
				$return = $returnvalue ? $v : true;
				return $return;
			}
		}
		return false;
	}
	
}